package com.csw.android.dev_utils.log.request

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.viewpager.widget.PagerAdapter
import com.csw.android.dev_utils.R
import com.csw.android.dev_utils.databinding.DevUtilsDialogRequestLogBinding
import com.csw.android.dev_utils.databinding.DevUtilsDialogRequestLogRequestPageBinding
import com.csw.android.dev_utils.utils.ToastUtils
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.tabs.TabLayout
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject

/**
 * BottomSheetDialog只能接受一个嵌套的子视图，多个的话无法嵌套滑动
 */
class RequestLogDialog(context: Context, val requestLogInfo: RequestLogInfo) :
    BottomSheetDialog(context) {
    private val dataBinding = DataBindingUtil.inflate<DevUtilsDialogRequestLogBinding>(
        LayoutInflater.from(context),
        R.layout.dev_utils_dialog_request_log,
        null,
        false
    )
    private val requestDataBinding =
        DataBindingUtil.inflate<DevUtilsDialogRequestLogRequestPageBinding>(
            LayoutInflater.from(context),
            R.layout.dev_utils_dialog_request_log_request_page,
            null,
            false
        )
    private val responseDataBinding =
        DataBindingUtil.inflate<DevUtilsDialogRequestLogRequestPageBinding>(
            LayoutInflater.from(context),
            R.layout.dev_utils_dialog_request_log_request_page,
            null,
            false
        )

    //    private val viewPagerAdapter = ViewPagerAdapter()
    private val requestHeadDataListener = Observer<String?> {
        requestDataBinding.header.text = it
    }
    private val requestDataListener = Observer<String?> {
        formatJson(it, requestDataBinding.content)
    }
    private val responseDataListener = Observer<String?> {
        formatJson(it, responseDataBinding.content)
    }

    init {
        dataBinding?.run {
            setContentView(root)
            title.run {
                text = "${requestLogInfo.getTime()}\n${requestLogInfo.getContent()}"
                setOnClickListener { view ->
                    (view.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).run {
                        setPrimaryClip(
                            ClipData.newPlainText(
                                "LogInfo",
                                requestLogInfo.toString()
                            )
                        )
                        ToastUtils.showShort("已复制到剪贴板")
                    }
                }
            }
//            viewPager.run {
//                adapter = viewPagerAdapter
//            }
            tabLayout.run {
                addTab(tabLayout.newTab().apply {
                    text = "Request"
                })
                addTab(tabLayout.newTab().apply {
                    text = "Response"
                })
                tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                    override fun onTabSelected(tab: TabLayout.Tab?) {
                        setPage(tab?.position ?: 0)
                    }

                    override fun onTabUnselected(tab: TabLayout.Tab?) {
                    }

                    override fun onTabReselected(tab: TabLayout.Tab?) {
                    }
                })
            }
        }
        requestDataBinding?.run {
            header.setOnClickListener { view ->
                val h = header.text
                if (h.isNotEmpty()) {
                    (view.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).run {
                        setPrimaryClip(ClipData.newPlainText("LogInfo", header.text.toString()))
                        ToastUtils.showShort("已复制到剪贴板")
                    }
                }
            }

            content.setOnClickListener { view ->
                (view.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).run {
                    setPrimaryClip(ClipData.newPlainText("LogInfo", content.text.toString()))
                    ToastUtils.showShort("已复制到剪贴板")
                }
            }
        }
        responseDataBinding?.run {
            content.setOnClickListener { view ->
                (view.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).run {
                    setPrimaryClip(ClipData.newPlainText("LogInfo", content.text.toString()))
                    ToastUtils.showShort("已复制到剪贴板")
                }
            }
        }
        setPage(0)
    }

    private fun setPage(index: Int) {
        when (index) {
            0 -> {
                requestDataBinding.root
            }
            else -> {
                responseDataBinding.root
            }
        }.apply {
            dataBinding.frameLayout.removeAllViews()
            dataBinding.frameLayout.addView(this)
        }
    }

    private val gson = GsonBuilder().serializeNulls().setPrettyPrinting().create()
    private fun formatJson(jsonString: String?, content: TextView) {
        val formatJson = try {
            val json = gson.fromJson(jsonString, JsonObject::class.java)
            gson.toJson(json)
        } catch (e: Exception) {
            e.printStackTrace()
            "${jsonString}\n\n ${e.message}"
        }
        content.text = formatJson
    }

    override fun show() {
        super.show()
        requestLogInfo.requestHeader.observeForever(requestHeadDataListener)
        requestLogInfo.request.observeForever(requestDataListener)
        requestLogInfo.response.observeForever(responseDataListener)
    }

    override fun dismiss() {
        requestLogInfo.requestHeader.removeObserver(requestHeadDataListener)
        requestLogInfo.request.removeObserver(requestDataListener)
        requestLogInfo.response.removeObserver(responseDataListener)
        super.dismiss()
    }

    private inner class ViewPagerAdapter : PagerAdapter() {

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            return when (position) {
                0 -> {
                    requestDataBinding.root
                }
                else -> {
                    responseDataBinding.root
                }
            }.apply {
                container.addView(this)
            }
        }

        override fun destroyItem(container: ViewGroup, position: Int, any: Any) {
            if (any is View) {
                container.removeView(any)
            }
        }

        override fun getCount() = 2

        override fun getPageTitle(position: Int): CharSequence? {
            return when (position) {
                0 -> "Request"
                else -> "Response"
            }
        }

        override fun isViewFromObject(view: View, any: Any): Boolean {
            return view == any
        }
    }

}